var gulp = require('gulp');//gulp库
var webpack = require("webpack");//webpack库
var sass = require('gulp-sass');//处理sass
var gulpReplace = require("gulp-replace");//替换html中的字符
var postcss = require('gulp-postcss');//自动添加css前缀
var minifycss = require('gulp-minify-css');//压缩css
var uglify=require('gulp-uglify');//压缩js
var fs=require('fs');//文件


var src="src";//开发目录
var dist="dist";//生成目录


/*------------------默认任务----------------*/
gulp.task('default',function () {
    //return;
    createjs();
    gulp.run('html');
    gulp.run('sass');
    gulp.run('copy');
});


/*------------------css预编译----------------*/
gulp.task('sass', function(){
    gulp.src([src+'/scss/*.scss','!**/function.scss','!**/ui_common.scss'])
   .pipe(sass())
   .pipe(postcss())
   .pipe(minifycss())
   .pipe(gulp.dest(dist+'/assets/css'));
});




/*------------------处理html文件----------------*/
gulp.task('html',function(){
   gulp.src(src+"/*.html")
   .pipe(gulpReplace('</body>',function(str) {
       var filename=this.file.relative.split('.html')[0];
       var scriptStr='<script src="./js/common.js"></script>\n' +
           '<script src="./js/vue.js"></script>\n' +
           '<script src="./js/'+filename+'.js"></script>\n';
       return scriptStr+str;
   }))
   .pipe(gulpReplace('</head>',function(str) {
       var linkStr='<link rel="stylesheet" href="assets/css/common.css">\n';
       return linkStr+str;
   }))
   .pipe(gulp.dest(dist+"/"));
});




/*------------------拷贝文件----------------*/
gulp.task('copy',function(){
    gulp.src([src+'/js/commonJS/**']).pipe(uglify()).pipe(gulp.dest(dist+'/js/'));
    gulp.src([src+'/assets/**/*.*']).pipe(gulp.dest(dist+'/assets/'));
});



/*------------------监听文件变化----------------*/
gulp.watch([src+"/js/commonJS/*.js"],function(){
    gulp.src([src+'/js/commonJS/*.js']).pipe(uglify()).pipe(gulp.dest(dist+'/js/'));
});

gulp.watch(src+"/assets/**/*.*",function(){
    gulp.src('/assets/**/*.*').pipe(gulp.dest(dist+'/assets/'));
});

gulp.watch(src+"/scss/*.scss",['sass']);
gulp.watch(src+"/*.html",['html']);
gulp.watch([src+"/js/*.js",src+"/js/**/**.vue"],createjs);



/*------------------webpack处理js-------------------*/
function createjs(res){
    let filename="",entryList=[];
    if(res){
        filename=res.path.split('\\');
        filename= filename[filename.length-1];
    }

    if(res && filename.indexOf('.js')>-1){
        entryList.push(filename);
    }else{
        let tmpList=fs.readdirSync('./src/js/');
        tmpList.forEach((v)=>{
            if(v.indexOf('.js')>-1){
                entryList.push(v);
            }
        })
    }
    entryList.forEach((v)=>{
        webpack(webpackConfig(v),function(error){
            if(!error){
                console.log("["+new Date().toLocaleTimeString()+"]",'Finished',v);
            }else{
                console.log("["+new Date().toLocaleTimeString()+"]","Error",v,error);
            }
        });
    });

}

function webpackConfig(filename){
    let config={
        entry:__dirname+"/src/js/"+filename,
        output:{
            path: __dirname+"/dist/js/",
            filename:filename
        },
        module:{
            loaders:[
                {
                    test:/(\.vue)$/,
                    loader:'vue-loader',
                    //options:{extractCSS:true}
                },
                {test: /(\.js)$/,loader:'babel-loader',query:{presets: ['es2015']}}
            ]
        },
        plugins:[
            //new webpack.optimize.UglifyJsPlugin()
        ]
    };
    return config;
}